﻿using CommandService;
using Entity;
using Entity.DbEntity.sys;
using Entity.FrameEntity;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SysFramework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Tools;
using static System.Net.Mime.MediaTypeNames;

namespace BLL
{
    public class InventoryBLL : PubMethod
    {
        ReturnResult rsl;
        Commands cmd;
        SystemManagement sysBLL;
        OutBaseHelper outBase;
        public ILog log = LogManager.GetLogger(typeof(InventoryBLL));
        public InventoryBLL()
        {
            rsl = new ReturnResult();
            cmd = new Commands();
            sysBLL = new SystemManagement();
            outBase = new OutBaseHelper();
        }
        /// <summary>
        /// 同步存货档案方法
        /// </summary>
        /// <param name="userCode">当前登录人</param>
        /// <param name="baseCode">erp账套号</param>
        /// <param name="isAuto">是否自动任务</param>
        /// <param name="syncClass">是否同步存货大类</param>
        /// <returns></returns>
        public ReturnResult SyncInventory(string userCode, string baseCode, bool isAuto = false, bool syncClass = false)
        {
            rsl = new ReturnResult();
            try
            {
                log.Info("存货档案数据开始同步");
                if (syncClass)
                {
                    rsl = this.SyncInventoryClass(userCode, baseCode);
                }
                else
                {
                    rsl.Result = true;
                }

                if (rsl.Result)
                {
                    rsl = this.SyncInventoryData(baseCode, userCode, isAuto);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 存货大类数据同步
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        public ReturnResult SyncInventoryClass(string userCode, string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                var table = InventoryClassDataU8(baseCode);
                //获取系统自身存货大类数据
                var qTable = cmd.GetDataTable("select * from fun_CommonTree_info where baseCode='" + baseCode + "' and trType='ptype'");//系统现有所有

                List<OperateModel> list = new List<OperateModel>();
                OperateModel oper;
                if (table.Rows.Count > 0)
                {
                    if (qTable.Rows.Count < 1)
                    {
                        oper = new OperateModel();
                        DbCommomTree commomTree = new DbCommomTree();
                        commomTree.trName = "存货大类";
                        commomTree.trType = "ptype";
                        commomTree.memo = "存货大类(自动)";
                        commomTree.isdel = 0;
                        commomTree.trCode = "prot";
                        commomTree.baseCode = baseCode;
                        oper.Data = commomTree;
                        oper.Types = OperateModel.OperateType.Add;
                        list.Add(oper);
                    }
                    var dr = table.Select("iInvCGrade =1");//获取第一级菜单
                    foreach (DataRow r in dr)
                    {
                        oper = new OperateModel();
                        this.createInventoryClassPar(r, ref oper, qTable, baseCode, userCode, "prot");
                        list.Add(oper);
                        this.CallBackInventoryClass(table, 2, r["cInvCCode"].ToString(), ref list, qTable, baseCode, userCode);
                    }
                }
                if (list.Count > 0)
                {
                    rsl = cmd.MoreUpdate(list);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// U8存货大类
        /// </summary>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        private DataTable InventoryClassDataU8(string baseCode)
        {
            string sql = "select * from InventoryClass ";
            var table = outBase.getData(sql, baseCode);//获取U8所有数据
            return table;
        }
        #region 存货大类构建参数方法
        /// <summary>
        /// 存货大类构建参数方法
        /// </summary>
        /// <param name="r">查询结果行</param>
        /// <param name="oper">操作模型</param>
        /// <param name="qTable">查询数据源</param>
        /// <param name="baseCode">账套</param>
        /// <param name="isAuto">是否是自动任务</param>
        private void createInventoryClassPar(DataRow r, ref OperateModel oper, DataTable qTable, string baseCode, string userCode, string parentCode)
        {
            var query = qTable.Select("trCode='" + r["cInvCCode"].ToString() + "'");
            //var query = qTable.Select("cCode='" + r["cInvCCode"].ToString() + "'");
            bool isAdd = true;
            if (query.Length > 0)
            {
                isAdd = false;
            }
            #region 同步到CommonTree
            DbCommonTree venClass = new DbCommonTree();
            venClass.baseCode = baseCode;
            venClass.trCode = r["cInvCCode"].ToString();
            venClass.trName = r["cInvCName"].ToString();
            venClass.trType = "ptype";
            venClass.isSync = "Y";
            venClass.parentCode = parentCode;
            venClass.isdel = 0;
            venClass.memo = "存货大类";
            if (isAdd)
            {
                #region 只有在添加状态下 下列值才会添加
                venClass.createtime = getNow();
                venClass.createuser = userCode;
                #endregion
                oper.Types = OperateModel.OperateType.Add;
            }
            else
            {
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "trCode,baseCode,trType";
            }
            oper.Data = venClass;
            #endregion

        }
        #endregion

        #region 存货大类递归方法
        /// <summary>
        /// 存货大类递归方法
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="gradeNum">类序号</param>
        /// <param name="cCode">编码</param>
        /// <param name="sysTable">系统目标数据表(查询)</param>
        /// <param name="list"></param>
        private void CallBackInventoryClass(DataTable dt, int gradeNum, string cCode, ref List<OperateModel> list, DataTable sysTable, string baseCode, string userCode)
        {
            var dr = dt.Select("cInvCCode like '" + cCode + "%' and iInvCGrade=" + gradeNum);
            if (dr.Length > 0)
            {
                OperateModel oper;

                foreach (DataRow r in dr)
                {
                    oper = new OperateModel();
                    createInventoryClassPar(r, ref oper, sysTable, baseCode, userCode, cCode);
                    list.Add(oper);
                    CallBackInventoryClass(dt, gradeNum + 1, r["cInvCCode"].ToString(), ref list, sysTable, baseCode, userCode);
                }
            }
        }
        #endregion

        /// <summary>
        /// 存货数据同步(U8)
        /// </summary>
        /// <param name="baseCode"></param>
        /// <param name="userCode"></param>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        private ReturnResult SyncInventoryData(string baseCode, string userCode, bool isAuto)
        {
            rsl = new ReturnResult();
            try
            {

                if (string.IsNullOrWhiteSpace(baseCode))
                {
                    rsl.Message = "数据库编码获取失败";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                var table = this.InventoryDataU8(isAuto, baseCode);
                sb.Append("select * from fun_Inventory_Info where baseCode='" + baseCode + "'");
                var proTable = cmd.GetDataTable(sb.ToString());//关联账套全部存货数据
                sb.Clear();
                sb.Append("select * from sys_dictionaries_info where types='prt' and status=1");
                var uTable = cmd.GetDataTable(sb.ToString());
                List<OperateModel> list = new List<OperateModel>();
                DbInventory ven;
                OperateModel oper;
                if (table.Rows.Count > 0)
                {
                    #region 构建数据
                    foreach (DataRow r in table.Rows)
                    {
                        oper = new OperateModel();

                        ven = new DbInventory();
                        ven.isDel = 0;
                        ven.isSync = "Y";
                        ven.proCode = r["proCode"].ToString().Trim();
                        ven.proName = r["proName"].ToString();
                        ven.typeCode = r["typeCode"].ToString();
                        ven.mUnit = r["mUnit"].ToString();
                        ven.cUnit = r["cUnit"].ToString();
                        ven.spec = r["spec"].ToString();
                        var mUnitName = r["mUnitName"].ToString();
                        var dr = uTable.Select("name='" + mUnitName + "'");
                        if (dr.Length > 0)
                        {
                            ven.sysUnit = dr[0]["code"].ToString();
                        }
                        else
                        {
                            foreach (DataRow ur in uTable.Rows)
                            {
                                if (ur["extendFile"] != null && ur["extendFile"].ToString() == "1")
                                {
                                    ven.sysUnit = ur["code"].ToString();
                                    break;
                                }
                            }
                        }
                        ven.baseCode = baseCode;

                        if (string.IsNullOrWhiteSpace(r["dEDate"].ToString()) || DateTime.Parse(r["dEDate"].ToString()).Year < 2022)
                        {
                            ven.status = "Y";
                        }
                        else
                        {
                            ven.status = "N";
                        }
                        dr = proTable.Select("proCode='" + r["proCode"].ToString().Trim() + "'");
                        if (dr.Length < 1)
                        {
                            ven.createtime = getNow();
                            ven.createuser = userCode;
                            oper.Types = OperateModel.OperateType.Add;
                        }
                        else
                        {
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "proCode,baseCode";
                        }

                        oper.Data = ven;
                        list.Add(oper);
                    }
                    #endregion
                }
                else
                {
                    rsl.Message = "更新完成(无数据)";
                    rsl.Result = true;
                }
                string msg = "";
                sysBLL.SubmitSyncData(list, "存货同步", ref msg);
                if (string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Result = true;
                }
                else
                {
                    rsl.Result = false;
                    rsl.Message = msg;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 存货档案数据(U8)
        /// </summary>
        /// <param name="isAuto"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        private DataTable InventoryDataU8(bool isAuto, string baseCode)
        {
            string paCode = "";
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from sys_parameters_info where parCode='banGun'");
            var parTable = cmd.GetDataTable(sb.ToString());
            if (parTable.Rows.Count > 0)
            {
                paCode = parTable.Rows[0]["parValue"].ToString();
            }
            sb.Clear();
            //编码、名称、类编码、规格、规格
            sb.Append("select p.cInvCode proCode,p.cInvName proName,p.cInvCCode typeCode,isnull(p.cInvStd,'') spec ");
            //主计量单位编码、辅助计量单位编码、主计量名称
            sb.Append(",p.cComUnitCode mUnit,isnull(p.cAssComUnitCode,'') cUnit,mu.cComUnitName mUnitName,");
            //辅计量名称、停用日期
            sb.Append("isnull(cu.cComUnitName,'') cUnitName,isnull(dEDate,'') dEDate");
            sb.Append("  from inventory p inner join ComputationUnit mu on p.cComUnitCode=mu.cComUnitCode");
            sb.Append(" left join ComputationUnit cu on p.cAssComUnitCode=cu.cComunitCode");
            sb.Append(" where 1=1  ");//09为版辊大类，同步存货不同步版辊档案
            if (!string.IsNullOrWhiteSpace(paCode))
            {
                sb.Append(" and cInvCCode !='" + paCode + "'");
            }
            if (!isAuto)
            {
                string value = string.Format("-{0}", AppSettingHelper.ReadAppSettings("SyncInventoDay"));
                string qydate = DateTime.Now.AddDays(double.Parse(value)).ToString("yyyy-MM-dd");
                sb.Append(" and dModifyDate>='" + qydate + "'");//修改时间
            }
            return outBase.getData(sb.ToString(), baseCode);
        }


        /// <summary>
        /// 存货列表(分页)
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult InventoryList(string pageIndex, string pageSize, string condition, string baseCode, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0  and baseCode='" + baseCode + "' ");

                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
  
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            sb.Append(" and ");
                            if (obj.Name == "typeCode" && obj.Value.ToString() != "prot")
                            {
                                sb.Append(obj.Name + " like '" + obj.Value.ToString() + "%' ");
                            }
                            else if (obj.Name != "typeCode" )
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                var list = cmd.PageList("V_Products_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        
        /// <summary>
        /// 存货现存量列表(分页)
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getStockList( string baseCode, string condition)
        {
            rsl = new ReturnResult();
            OutBaseHelper outDb = new OutBaseHelper();
            try
            {
                StringBuilder sb = new StringBuilder();
                var json = JsonConvert.DeserializeObject<JObject>(condition);

                sb.Append("select top 2000 s.cInvCode proCode,i.cInvName proName,cInvStd spec,s.cBatch,SUM(Convert(decimal(18, 2), iQuantity)) number ");
                sb.Append(",'' cjStock from CurrentStock s ");
                sb.Append("inner join Inventory i on s.cInvCode = i.cInvCode ");
                #region 检索条件
                if (!string.IsNullOrWhiteSpace(json["cInvCode"].ToString()))
                {
                    sb.Append(" and  s.cInvCode  like '%" + json["cInvCode"].ToString().Trim() + "%' ");
                }
                if (!string.IsNullOrWhiteSpace(json["cInvName"].ToString()))
                {
                    sb.Append(" and  i.cInvName  like '%" + json["cInvName"].ToString().Trim() + "%' ");
                }
                if (!string.IsNullOrWhiteSpace(json["cInvStd"].ToString()))
                {
                    sb.Append(" and  i.cInvStd  like '%" + json["cInvStd"].ToString().Trim() + "%' ");
                }
                #endregion
                sb.Append("group by s.cInvCode,i.cInvName,cInvStd,s.cBatch ");
                sb.Append("having SUM(Convert(decimal(18, 2), iQuantity)) > 0 ");
                var table = outDb.getData(sb.ToString(), baseCode);

                var work_sql = "select parValue from sys_parameters_info where parCode = 'work_warehouse_code' ";
                var wt = cmd.GetDataTable(work_sql);   //获取车间库编码
                //var workCode = "8";
                var workCode = "";
                if (wt.Rows.Count > 0)
                {
                    //workCode = wt.Rows[0]["parValue"].ToString();
                    #region 多个仓库（Ning）
                    //var workCode = "";
                    var ware = cmd.GetDataTable(work_sql).Rows[0]["parValue"].ToString();
                    var lists = ware.Split(',');
                    for (int i = 0; i < lists.Length; i++)
                    {
                        workCode += "'" + lists[i].ToString() + "',";
                    }
                    workCode = workCode.TrimEnd(',');
                    #endregion
                }
                //if (wt.Rows.Count > 0)
                //    workCode = wt.Rows[0]["parValue"].ToString();

                foreach (DataRow dr in table.Rows)
                {
                    sb.Clear();
                    sb.Append("select isNull(SUM(Convert(decimal(18, 2), iQuantity)),0) cjStock  ");
                    //sb.Append("from CurrentStock where cWhCode='"+ workCode + "' ");
                    sb.Append("from CurrentStock where cWhCode in (" + workCode + ") ");
                    sb.Append("and cInvCode='" + dr["proCode"].ToString() + "' and cBatch='" + dr["cBatch"].ToString() + "' ");
                    var dt = outDb.getData(sb.ToString(), baseCode);

                    dr["cjStock"] = dt.Rows[0][0].ToString();
                }

                var list = cmd.TableToDictionary(table);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 版辊数据同步
        /// </summary>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        public ReturnResult SyncBanGunData(string baseCode)
        {
            rsl = new ReturnResult();
            List<OperateModel> operList = new List<OperateModel>();
            OperateModel oper;
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_BanYang_list where dTypes='bg'");//获取全部版辊信息
                var bgTable = cmd.GetDataTable(sb.ToString());
                var erpTable = this.ErpBanGun(baseCode);
                DbBanGun bg;
                foreach (DataRow r in bgTable.Rows)
                {
                    var dr = erpTable.Select("proCode='" + r["erpProCode"].ToString() + "'");
                    if (dr.Length > 0)
                    { //修改版信息
                        bg = new DbBanGun();
                        bg.erpProCode= dr[0]["proCode"].ToString();
                        bg.banchang = dr[0]["banchang"].ToString();
                        bg.banzhou = dr[0]["banzhou"].ToString();
                        bg.baseCode = baseCode;
                        bg.byName = dr[0]["proName"].ToString();
                        //bg.cuName = dr[0]["cuName"].ToString();
                        oper = new OperateModel();
                        oper.Data = bg;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "erpProCode";
                        operList.Add(oper);
                    }
                }
                string msg = "";
                sysBLL.SubmitSyncData(operList, "版辊信息同步", ref msg);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 版辊入库单数据同步
        /// </summary>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        public ReturnResult SyncBanGunInData(string baseCode)
        {
            rsl = new ReturnResult();
            List<OperateModel> operList = new List<OperateModel>();
            OperateModel oper;
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_BanYang_list ");//获取全部版辊信息    where relationErpCode is null or relationErpCode=''
                var bgTable = cmd.GetDataTable(sb.ToString());
                var erpTable = this.ErpBanGunIn(baseCode);
                DbBanGun bg;
                foreach (DataRow r in erpTable.Rows)
                {
                    var dr = bgTable.Select("byCode='" + r["byCode"].ToString() + "'");

                    if (dr.Length <= 0)
                    { //已经存在版辊记录不做任何操作，不存在做添加操作
                        double money = 0;
                        if (!string.IsNullOrEmpty(r["uPrice"].ToString()))
                        {
                            money = double.Parse(r["uPrice"].ToString());
                        }
                        bg = new DbBanGun();
                        bg.byBarCode = r["byCode"].ToString();
                        bg.byCode = r["byCode"].ToString();
                        bg.erpProCode= r["proCode"].ToString();
                        bg.money = Math.Round(money, 2).ToString();
                        bg.wareHouse = r["wareHourse"].ToString();
                        bg.supCode = r["supCode"].ToString();
                        bg.batch = r["pici"].ToString();
                        bg.relationErpCode = r["orderCode"].ToString();
                        bg.isdel = 0;
                        bg.createtime = getNow();
                        bg.createuser = "admin";
                        bg.status = "need-out";
                        bg.dTypes = "bg";
                        bg.isfb = "0";
                        //bg.warPostion = "";
                        //bg.memo = "";
                        oper = new OperateModel();
                        oper.Data = bg;
                        oper.Types = OperateModel.OperateType.Add;
                        //oper.Conditions = "byBarCode";
                        operList.Add(oper);
                    }
                }
                string msg = "";
                sysBLL.SubmitSyncData(operList, "版辊入库信息同步", ref msg);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// erp版辊数据信息
        /// </summary>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        private DataTable ErpBanGun(string baseCode)
        {
            string paCode = "NA";
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from sys_parameters_info where parCode='banGun'");
            var parTable = cmd.GetDataTable(sb.ToString());
            if (parTable.Rows.Count > 0)
            {
                var obj = JsonConvert.DeserializeObject<JObject>(parTable.Rows[0]["parValue"].ToString());
                paCode = obj["bgTypeCode"].ToString();
            }
            sb.Clear();
            //编码、名称、类编码、规格、规格   
            sb.Append("select p.cInvCode proCode,p.cInvName proName,p.cInvCCode typeCode,isnull(p.cInvStd,'') spec ");
            //主计量单位编码、辅助计量单位编码、主计量名称
            sb.Append(",p.cComUnitCode mUnit,isnull(p.cAssComUnitCode,'') cUnit,mu.cComUnitName mUnitName,");
            //版长、版周、客户
            sb.Append("p.cInvDefine1 banzhou,p.cInvDefine2 banchang,cInvDefine3 cuName, ");
            //辅计量名称、停用日期
            sb.Append("isnull(cu.cComUnitName,'') cUnitName,isnull(dEDate,'') dEDate");
            sb.Append("  from inventory p inner join ComputationUnit mu on p.cComUnitCode=mu.cComUnitCode");
            sb.Append(" left join ComputationUnit cu on p.cAssComUnitCode=cu.cComunitCode");
            sb.Append(" where p.cInvCCode='" + paCode + "'");
            //if (AppSettingHelper.ReadAppSettings("IsDevelop") != "1")
            //{//非开发版本，只获取最近几日的数据
            //    sb.Append(" and DateDiff(dd,dSDate,getdate())<=" + AppSettingHelper.ReadAppSettings("SyncInventoDay"));
            //}
            return outBase.getData(sb.ToString(), baseCode);
        }
        /// <summary>
        /// 版辊入库数据
        /// </summary>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        private DataTable ErpBanGunIn(string baseCode)
        {
            string paCode = "NA";
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from sys_parameters_info where parCode='banGun'");
            var parTable = cmd.GetDataTable(sb.ToString());
            if (parTable.Rows.Count > 0)
            {
                var obj = JsonConvert.DeserializeObject<JObject>(parTable.Rows[0]["parValue"].ToString());
                paCode = obj["inOutType"].ToString();
            }
            sb.Clear();
            sb.Append("select c.cInvCode proCode,c.iQuantity number,c.iUnitCost uPrice,m.cWhCode wareHourse,m.cVenCode supCode,");
            sb.Append("c.cBatch pici,m.cCode orderCode,c.cFree1 byCode from RdRecords01 c inner join RdRecord01 m on m.id=c.id  ");
            sb.Append("where m.cRdCode='" + paCode + "' and m.bredvouch=0 ");  //and (m.dModifyDate is not null or m.dModifyDate !='')
            if (AppSettingHelper.ReadAppSettings("IsDevelop") != "1")
            {//非开发版本，只获取最近几日的数据
                sb.Append(" and DateDiff(dd,dVeriDate,getdate())<=" + AppSettingHelper.ReadAppSettings("SyncInventoDay") );  
            }
            return outBase.getData(sb.ToString(), baseCode);

        }
        /// <summary>
        /// 查找存货
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public ReturnResult SearchInventories(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var filterDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                //var proCode = filterDic["proCode"];
                //var proName = filterDic["proName"];
                //var spec = filterDic["spec"];

                var searchSb = new StringBuilder();

                //searchSb.Append("select top 100 * from fun_Inventory_Info where isdel = 0 ");
                searchSb.Append("select top 100 i.*,d.name proUnit from fun_Inventory_Info i left join sys_dictionaries_info d on d.types='prt' and d.code=i.sysUnit and d.status='1' where isdel = 0 ");

                var whereSb = new StringBuilder();
                foreach (var key in filterDic.Keys)
                {
                    var filterValue = filterDic[key];

                    if (!string.IsNullOrEmpty(filterValue))
                    {
                        whereSb.Append(" and ");
                        whereSb.Append(key + " like '%");
                        whereSb.Append(filterValue);
                        whereSb.Append("%' ");
                    }
                }

                searchSb.Append(whereSb.ToString());

                var dt = cmd.GetDataTable(searchSb.ToString());

                var returnListDic = cmd.TableToDictionary(dt);

                rsl.Result = true;
                rsl.Data = returnListDic;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 查找用户
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public ReturnResult SearchUsers(string json)
        {
            rsl = new ReturnResult();
            try
            {
                var filterDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                //var proCode = filterDic["proCode"];
                //var proName = filterDic["proName"];
                //var spec = filterDic["spec"];

                var searchSb = new StringBuilder();

                var gxCode = filterDic["gxCode"];

                searchSb.Append($@"select top 100 * from sys_users_info where isdel = 0 and userCode in (select usCode from pi_GongXuUser_set where GongXu = '{gxCode}') ");

                filterDic.Remove("gxCode");

                var whereSb = new StringBuilder();
                foreach (var key in filterDic.Keys)
                {
                    var filterValue = filterDic[key];

                    if (!string.IsNullOrEmpty(filterValue))
                    {
                        whereSb.Append(" and ");
                        whereSb.Append(key + " like '%");
                        whereSb.Append(filterValue);
                        whereSb.Append("%' ");
                    }
                }

                searchSb.Append(whereSb.ToString());

                var dt = cmd.GetDataTable(searchSb.ToString());

                var returnListDic = cmd.TableToDictionary(dt);

                rsl.Result = true;
                rsl.Data = returnListDic;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult GetProductByCode(string proCode)
        {
            rsl = new ReturnResult();
            try
            {
                string sql = "select * from v_Products_info where proCode='" + proCode + "'";
                var pTable = cmd.GetDataTable(sql);
                if (pTable.Rows.Count > 0)
                {
                    rsl.Result = true;
                    rsl.Data = cmd.TableToDictionary(pTable);
                }
                else
                {
                    rsl.Result = false;
                    rsl.Message = "没有数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
}
